//
//  SDBasePaientListController.m
//  SKinDiary
//
//  Created by pcyang on 16/7/16.
//  Copyright © 2016年 tencent. All rights reserved.
//

#import "SDBasePaientListController.h"
#import "SDPaientEditorViewController.h"
#import "SDPaientInfoViewController.h"
#import "SDNavigationController.h"
#import "ZYPinYinSearch.h"
#import "HCSortString.h"
#import "SDPaientInfoMgr.h"
#import "SDPaientInfoItem.h"
#import "SDPaientItemCell.h"
#import "SDWindowManager.h"
#import "SDPaientListData.h"

@interface SDBasePaientListController ()<UITableViewDelegate,UITableViewDataSource,UISearchBarDelegate,SDBaseDataDelegate>
@property(nonatomic,strong)SDPaientListData* paientListData;

@end

@implementation SDBasePaientListController
- (void)viewDidLoad {
    [super viewDidLoad];
    [self initSubviews];
    [self initData];
    [self loadData];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onAddPaientNotification:) name:kAddNewPaientSuccessNotification object:nil];

//    SDLoginManager* loginMgr = [SDLoginManager sharedInstance];
//    if ([loginMgr isLogin]) {
//        [_paientListData reloadDataWithCache:NO];
//    }
}

-(void)initData
{
    _paientListData = [[SDPaientListData alloc] init];
    _paientListData.delegate = self;
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear: animated];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (BOOL)navigationBarHidden
{
    return NO;
}

-(void)initSubviews
{
    [self.view addSubview:self.friendTableView];
    [self.view addSubview:self.searchBar];
}

#pragma mark - Init
- (void)loadData {
    _searchDataSource = [NSMutableArray new];
    
    SDPaientInfoMgr* suffererInfoMgr = [SDPaientInfoMgr shareAGDatabaseManager];
    _dataSource = [suffererInfoMgr selectALL:[SDPaientInfoItem class] tableName:kPaientTableName];
    
    _allDataSource = [HCSortString sortAndGroupForArray:_dataSource PropertyName:@"name"];
    _indexDataSource = [HCSortString sortForStringAry:[_allDataSource allKeys]];
    
}

- (UITableView *)friendTableView {
    if (!_friendTableView) {
        _friendTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, self.navBar.bottom + 44, kScreenWidth, kScreenHeight- MainTabBar_H - self.navBar.bottom - 44) style:UITableViewStylePlain];
        //_friendTableView.backgroundColor = kColor;
        _friendTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _friendTableView.delegate = self;
        _friendTableView.dataSource = self;
    }
    return _friendTableView;
}

- (UISearchBar *)searchBar {
    if (!_searchBar) {
        _searchBar = [[UISearchBar alloc]initWithFrame:CGRectMake(0, self.navBar.bottom, kScreenWidth, 44)];
        _searchBar.backgroundImage = [[UIImage alloc] init];
        // 设置SearchBar的颜色主题为白色
        _searchBar.barTintColor = [UIColor colorWithRGB:0x24d9c6];
        _searchBar.backgroundColor = [UIColor colorWithRGB:0x24d9c6];
        _searchBar.delegate = self;
        _searchBar.placeholder = @"搜索";
        _searchBar.showsCancelButton = NO;
        
        UITextField *searchField = [_searchBar valueForKey:@"searchField"];
        if (searchField) {
            [searchField setBackgroundColor:[UIColor whiteColor]];
            searchField.layer.cornerRadius = 14.0f;
            searchField.layer.borderColor = [UIColor whiteColor].CGColor;
            searchField.layer.borderWidth = 1;
            searchField.layer.masksToBounds = YES;
        }
        _searchBar.tintColor = [UIColor whiteColor];
        //修正光标颜色
        //   [searchField setTintColor:[UIColor blackColor]];
    }
    return _searchBar;
}

-(void)reloadData
{
    [self loadData];
    [_friendTableView reloadData];
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if (!_isSearch) {
        return _indexDataSource.count;
    }else {
        return 1;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (!_isSearch) {
        NSArray *value = [_allDataSource objectForKey:_indexDataSource[section]];
        return value.count;
    }else {
        return _searchDataSource.count;
    }
}
//头部索引标题
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    if (!_isSearch) {
        return _indexDataSource[section];
    }else {
        return nil;
    }
}
//右侧索引列表
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
    if (!_isSearch) {
        return _indexDataSource;
    }else {
        return nil;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    SDPaientItemCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
    if (cell == nil) {
        cell = [[SDPaientItemCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Cell"];
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    }
    if (!_isSearch) {
        NSArray *value = [_allDataSource objectForKey:_indexDataSource[indexPath.section]];
        SDPaientInfoItem* userItem = value[indexPath.row];
        //cell.textLabel.text = value[indexPath.row];
        [cell setCellData:userItem];
        
    }else{
        SDPaientInfoItem* userItem = _searchDataSource[indexPath.row];
        [cell setCellData:userItem];
        
    }
    return cell;
}
//索引点击事件
- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
    [tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:index] atScrollPosition:UITableViewScrollPositionTop animated:YES];
    return index;
}

#pragma mark - Table View Delegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return kPaientCellHeight;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    SDPaientInfoItem* paientInfo;
    if (!self.isSearch) {
        NSArray *value = [self.allDataSource objectForKey:self.indexDataSource[indexPath.section]];
        paientInfo = value[indexPath.row];
    //    self.block(userItem);
    }else{
       // self.block(self.searchDataSource[indexPath.row]);
        paientInfo = self.searchDataSource[indexPath.row];
    }
    [self searchBarCancelButtonClicked:self.searchBar];
    SDPaientInfoViewController* paientInfoVC = [[SDPaientInfoViewController alloc] init];
    paientInfoVC.paientItem = paientInfo;
    [self.navigationController pushViewController:paientInfoVC animated:YES];
}

#pragma mark - UISearchBarDelegate
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
    [_searchDataSource removeAllObjects];
    NSArray *ary = [HCSortString getAllValuesFromDict:_allDataSource];
    
    if (searchText.length == 0) {
        _isSearch = NO;
        [_searchDataSource addObjectsFromArray:ary];
    }else {
        _isSearch = YES;
        ary = [ZYPinYinSearch searchWithOriginalArray:ary andSearchText:searchText andSearchByPropertyName:@"name"];
        [_searchDataSource addObjectsFromArray:ary];
    }
    [self.friendTableView reloadData];
}

- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
    [UIView animateWithDuration:0.3 animations:^{
        self.navBar.hidden = YES;
        _searchBar.frame = CGRectMake(0, kNaviOrigenY, kScreenWidth, 44);
        _searchBar.top = kNaviOrigenY;
        _friendTableView.top = _searchBar.bottom;
        _searchBar.showsCancelButton = YES;
    }];
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
    self.navBar.hidden = NO;
    _searchBar.top = self.navBar.bottom;
    _friendTableView.top = _searchBar.bottom;
    // _searchBar.frame = CGRectMake(0, self.navigationController.navigationBar.bottom, kScreenWidth, 44);
    _searchBar.showsCancelButton = NO;
    [_searchBar resignFirstResponder];
    _searchBar.text = @"";
    _isSearch = NO;
    [_friendTableView reloadData];
}

#pragma mark- Notification
-(void)onAddPaientNotification:(NSNotification*)notification
{
    [self reloadData];
}

#pragma mark - block
- (void)didSelectedItem:(SelectedItem)block {
    self.block = block;
}

#pragma mark -SDBaseDataDelegate
- (void)dataWillStartLoad:(SDBaseData*)model
{
    
}

- (void)data:(SDBaseData*)model didFinishLoadWithError:(NSError*)error nextDataType:(SDBaseDataType)nextDataType
{
    if (!error) {
        if ([model isKindOfClass:[SDPaientListData class]]) {
            SDPaientInfoMgr* dataBaseMgr = [SDPaientInfoMgr shareAGDatabaseManager];
            for (SDPaientInfoItem* infoItem in _paientListData.paientList) {
                NSArray* paientList = [dataBaseMgr select:[SDPaientInfoItem class] tableName:kPaientTableName where:[NSString stringWithFormat:@"pId = %ld",infoItem.pId]];
                if (!CHECK_VALID_ARRAY(paientList)) {
                    BOOL success = [dataBaseMgr insert:infoItem tableName:kPaientTableName];
                    if (success) {
                    }
                }
            }
            [self loadData];
            [self.friendTableView reloadData];
        }
    } else {
        
    }
}
@end
